package com.lnsoft.cac.server.handle.codec.frameMessage;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Data;
import lombok.NonNull;

import java.util.ArrayList;
import java.util.List;

@Data
/**
 * 配置/状态交互---通信流量信息查询
 * */
public class Cfg_Flow_Cfm {
    private int StatTime;           //4byte         采集时间
    private int MeasureData_Num;    //1byte         监测数据个数（无符号整数）
    private List<Cfg_Flow_Data_Cfm> Items;     //  统计条目

    public ByteBuf toByteBuf() throws Exception{
        if (!Util.statTimeIsAvailable(StatTime)) {
            throw new Exception("采集时间 设置异常");
        }
        if (!Util.measureDataNumIsAvailable(MeasureData_Num)) {
            throw new Exception("监测数据个数 设置异常");
        }
        if (Items == null) {
            Items = new ArrayList<>();
        }
        if (Items.size() != MeasureData_Num) {
            throw new Exception("数据个数 和 统计条目数量不一致");
        }
        ByteBuf bf = Unpooled.buffer(1453);
        bf.writeIntLE(StatTime);
        bf.writeByte(MeasureData_Num);
        for (Cfg_Flow_Data_Cfm item : Items) {
            bf.writeBytes(item.toByteBuf());
        }
        return bf;
    }



    //  解析 { 配置/状态交互---通信流量信息查询} 帧报文内容区 到消息体中
    public static Cfg_Flow_Cfm decFrameBody(@NonNull byte[] frameBody) throws Exception {
        ByteBuf bf = Unpooled.wrappedBuffer(frameBody);
        Cfg_Flow_Cfm msg = new Cfg_Flow_Cfm();
        int len = frameBody.length;
        if (len == 0) {
            return null;
        }
        msg.setStatTime(bf.getIntLE(0) & 0xFFFFFFFF);
        int num = bf.getByte(4) & 0xFF;
        if (len != num * 12 + 5) {
            throw new Exception("frameBody 异常");
        }
        msg.setMeasureData_Num(bf.getByte(4) & 0xFF);

        List<Cfg_Flow_Data_Cfm> list = new ArrayList();
        for (int i = 0; i < num; i++) {
            Cfg_Flow_Data_Cfm item = new Cfg_Flow_Data_Cfm();
            item.setStat_Time(bf.getIntLE(5 + i * 12) & 0xFFFFFFFF);
            item.setSend_Flow(bf.getIntLE(9 + i * 12) & 0xFFFFFFFF);
            item.setReceive_Flow(bf.getIntLE(13 + i * 12) & 0xFFFFFFFF);
            list.add(item);
        }
        msg.setItems(list);
        return msg;
    }

}
